package team

import (
	"sanguo/cluster"
	"sanguo/node/common/orderMap"
	"sanguo/node/node_team"
	"sanguo/node/node_team/com"
	ss_rpc "sanguo/protocol/ss/rpc"
	"sanguo/rpc/createTeam"
	"time"

	"github.com/golang/protobuf/proto"
)

type CreateTeam struct {
}

func (this *CreateTeam) OnCall(replyer *createTeam.CreateTeamReplyer, arg *ss_rpc.CreateTeamReq) {

	node_team.Debugln("OnCall CreateTeam", arg)

	r := &Role{}
	r.RoleID = arg.GetRoleID()
	r.UserID = arg.GetUserID()
	r.Level = arg.GetLevel()
	r.Name = arg.GetName()
	r.Portrait = arg.GetPortrait()
	r.Outline = arg.GetOutline()
	r.Face = arg.GetFace()
	r.Hair = arg.GetHair()
	r.HairColor = arg.GetHairColor()
	r.EyeColor = arg.GetEyeColor()
	r.Cloth = arg.GetCloth()
	r.ClothColor = arg.GetClothColor()
	r.Weapon1 = arg.GetWeapon1()
	r.Game = cluster.PeerID(arg.GetGame())
	r.Status = com.RoleStatus_Online

	resp := &ss_rpc.CreateTeamResp{
		Ok: proto.Int32(0),
	}

	teamID, err := com.TeamGenID()
	if err == nil {
		teamObj := &Team{
			TeamID:        teamID,
			TeamName:      arg.GetName() + "的队伍",
			TeamType:      arg.GetTeamType(),
			Header:        arg.GetRoleID(),
			Roles:         orderMap.NewOrderMap(),
			Status:        com.TeamStatus_Safe,
			NextHeartbeat: time.Now().Unix() + com.HeartBeatTimeout,
			AcceptApply:   com.AcceptApply_Request,
			ApplyRoles:    map[uint64]*ApplyRole{},
		}

		teamObj.AddRole(r)
		TeamMgr.RoleToTeam[r.RoleID] = teamObj

		TeamMgr.AddTeam(teamObj)

		resp.Ok = proto.Int32(1)
		resp.TeamID = proto.Uint64(teamID)
		replyer.Reply(resp)

		UpdateTeamToClients(teamObj)
		node_team.Infoln("CreateTeam OK", arg.GetUserID(), arg.GetRoleID())
	} else {
		node_team.Infoln("CreateTeam fail", arg.GetUserID(), err)
		replyer.Reply(resp)
	}

}

func init() {
	createTeam.Register(&CreateTeam{})
}
